package com.itheima.reggie.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.Cart;
import com.itheima.reggie.mapper.CartMapper;
import com.itheima.reggie.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;


// 购物车
@Service
@Transactional
public class CartServiceImpl implements CartService {

    @Autowired
    private CartMapper cartMapper;
    //添加购物车
    @Override
    public Cart add(Cart cartParam) {
        // 1.构建条件
        LambdaQueryWrapper<Cart> qw = new LambdaQueryWrapper<>();
        qw.eq(Cart::getUserId, UserHolder.get().getId()); // 用户id
        qw.eq(cartParam.getDishId()!=null,Cart::getDishId,cartParam.getDishId());//菜品id
        qw.eq(cartParam.getSetmealId()!=null,Cart::getSetmealId,cartParam.getSetmealId());//套餐id
        //2.调用mapper
        Cart cart = cartMapper.selectOne(qw);
        //3.判断
        if (cart == null) { // 不存在,新增
            cart = cartParam;
            cart.setId(IdUtil.getSnowflake(1,1).nextId());
            cart.setUserId(UserHolder.get().getId()); // 补全用户信息
            cart.setNumber(1); // 补全数量
            cart.setCreateTime(new Date()); //补全添加购物车时间
            // 3.1 调用mapper
            cartMapper.insert(cart);
        } else { // 存在,数量+1,更新数据库
            cart.setNumber(cart.getNumber()+1);
            cartMapper.updateById(cart);
        }
        //返回购物车
        return cart;
    }

    //查询购物车
    @Override
    public List<Cart> list() {
        // 1. 构建条件查询
        LambdaQueryWrapper<Cart> qw = new LambdaQueryWrapper<>();
        qw.eq(Cart::getUserId,UserHolder.get().getId());
        // 2.执行查询
        return cartMapper.selectList(qw);
    }

    //清空购物车
    @Override
    public void clean() {
        //1.构建条件
        LambdaQueryWrapper<Cart> qw = new LambdaQueryWrapper<>();
        qw.eq(Cart::getUserId,UserHolder.get().getId());
        //2.删除啊
        cartMapper.delete(qw);
    }

    //修改购物车
    @Override
    public Cart updateCart(Long dishId, Long setmealId) {
        // 1.查询需要修改的购物车对象
        // 1.1 构建条件
        LambdaQueryWrapper<Cart> qw = new LambdaQueryWrapper<>();
        qw.eq(Cart::getUserId,UserHolder.get().getId()); // 根据用户id
        qw.eq(dishId!=null , Cart::getDishId,dishId); // 菜品id
        qw.eq(setmealId!=null,Cart::getSetmealId,setmealId);// 套餐ID
        // 调用mapper
        Cart cart = cartMapper.selectOne(qw);
        //2.操作购物车数量-1
        if ((cart.getNumber() - 1) == 0) { // 如果==0,删除购物车记录
            cartMapper.deleteById(cart);
        } else { // 如果>0,更改购物车记录
            cart.setNumber(cart.getNumber()-1);
            cartMapper.updateById(cart);
        }
        return cart;
    }


}
